# 试图函数入口

# 使用蓝图装饰试图函数
from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import session

from info.models import User, News
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import news_blue



@news_blue.route('/<int:news_id>')
@user_login_data
def news_details(news_id):
    # 返回一个完整一个页面,render_template

    #  # 1.获取用户编号
    # user_id = session.get('user_id')
    #
    # # 2.查询用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    # 根据编号获取新闻对象
    try:
        news = News.query.get(news_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻失败')

    # 判断新闻是否存在,以后会做统一的404处理
    if not news:
        abort(404)

    # 将新闻的点击量加1
    news.clicks +=1

    # 查询热门新闻列表,取前8条
    try:
        news_items = News.query.order_by(News.clicks.desc()).limit(8)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='热门新闻查询失败')

    # 将新闻对象列表转成字典列表
    clicks_news_list = []
    for news in news_items:
        clicks_news_list.append(news.to_dict())




    # 3.拼接数据,渲染到页面
    data = {
        'user_info': g.user.to_dict() if g.user else '',
        'news': news.to_dict(),
        'clicks_news_list': clicks_news_list
    }


    return render_template('news/detail.html', data=data)


